package org.example.ftp.controller;

import org.example.ftp.entity.I18nTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContext;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.ResourceBundle;

//  https://mp.weixin.qq.com/s/zONMI8dmAVnmf58eRwYsrQ
//  https://mp.weixin.qq.com/s/vwX81gY6yexfqnIHw9cyxw  (推荐)
@RestController
@RequestMapping("/i18n")
public class TestI18nController {

    @Autowired
    private MessageSource messageSource;

    @PostMapping("/test1")
    public String test1() {
        return messageSource.getMessage("user.name", null, LocaleContextHolder.getLocale());
    }

    @PostMapping("/test2")
    public String test2(@RequestBody @Validated I18nTest i18nTest) {
        return messageSource.getMessage("user.name", null, LocaleContextHolder.getLocale());
    }

    @PostMapping("/test3")
    public void test3() {
        Locale locale = LocaleContextHolder.getLocale();
        System.out.println(locale);
        Locale localeEn = new Locale("en", "US");
        Locale localeZh = new Locale("zh", "CN");
        ResourceBundle res = ResourceBundle.getBundle("static/i18n/messages", localeEn);
        String hello = res.getString("user.name");
        System.out.println("user.name = " + hello);
    }

    //    DateFormat
    @PostMapping("/test4")
    public void test4() {
        Date date = new Date();
        DateFormat df = DateFormat.getDateInstance(DateFormat.LONG, new Locale("zh", "CN"));
        DateFormat df2 = DateFormat.getDateInstance(DateFormat.LONG, new Locale("en", "US"));
        System.out.println(df.format(date));
        System.out.println(df2.format(date));
    }

}
